package com.zzf.concurrent.example.design.pattern.guarded.suspension;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

/**
 * @author GaoFeng2017
 * @date 2019/9/8 9:36
 */
@Slf4j
public class RequestQueue<T> {

    private LinkedList<T> taskQueue;

    public RequestQueue() {
        taskQueue = new LinkedList<>();
    }

    /**
     * 获取队首元素
     * 如果队列没有元素，那么本次获取会被阻塞
     * @author ZengZhengFang
     * @date 2019/9/8 9:43
     * @param
     * @return T
     */
    public synchronized T get() {

        /** 队列没元素，则阻塞 */
        while (taskQueue.size() <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                return null;
            }
        }

        return taskQueue.removeFirst();
    }

    public synchronized boolean push(T task) {
        log.info("push the data into request queue -> {}", task);
        boolean isAdd = taskQueue.add(task);
        this.notifyAll();
        return isAdd;
    }
}
